package br.com.ordersys.web.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import br.com.ordersys.framework.utils.ExceptionUtils;

import com.googlecode.gwt.crypto.gwtx.io.InputStream;

public class UserPictureUtils {
	private static String FILE_NAME_PREFIX = "user_tmp_pict_";

	public static void saveFileOnTempFolder(HttpServletRequest req, MultipartFile file) throws Exception {
		File tmpFolder = (File) req.getServletContext().getAttribute("javax.servlet.context.tempdir");
		File tmpPicture = new File(tmpFolder, FILE_NAME_PREFIX + req.getSession().getId());

		if (tmpPicture.exists()) {
			tmpPicture.delete();
		}

		FileOutputStream fout = new FileOutputStream(tmpPicture);
		fout.write(file.getBytes());
		fout.flush();
		fout.close();
	}

	public static byte[] readFromTempFolder(HttpServletRequest req) {
		try {

			File tmpFolder = (File) req.getServletContext().getAttribute("javax.servlet.context.tempdir");
			File tmpPicture = new File(tmpFolder, FILE_NAME_PREFIX + req.getSession().getId());

			if (tmpPicture.exists()) {
				FileInputStream fin = new FileInputStream(tmpPicture);

				byte[] buf = new byte[512];
				int readen;
				ByteArrayOutputStream bout = new ByteArrayOutputStream();

				while ((readen = fin.read(buf)) > -1) {
					bout.write(buf, 0, readen);
				}

				bout.flush();
				fin.close();

				return bout.toByteArray();
			}

		} catch (Exception e) {
			ExceptionUtils.throwAsUnchecked(e);
		}
		return null;
	}

}
